package com.coolwen.spring.jdbc.dao;

import com.coolwen.spring.jdbc.model.Group;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.util.List;

/**
 * @author CoolWen
 * @version 2020-04-16 8:47
 */
@Repository("groupDao")
public class GroupDao implements IGroupDao {

    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void init(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public void add(Group group) {
        final String INSERT_SQL = "insert into t_group (group_name) values (?)";
        final String name = group.getGroupname();
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(connection -> {
            PreparedStatement ps = connection.prepareStatement(INSERT_SQL, new String[]{"id"});
            ps.setString(1, name);
            return ps;
        }, keyHolder);
        System.out.println(keyHolder.getKey());
        group.setId(keyHolder.getKey().intValue());
    }

    @Override
    public void delete(int id) {
        this.jdbcTemplate.update(
                "delete from t_group where id = ?",
                Long.valueOf(id));
    }

    @Override
    public void update(Group group) {
        this.jdbcTemplate.update(
                "insert into t_group (group_name) values (?)",
                group.getGroupname());
    }

    @Override
    public Group load(int id) {
        Group group = jdbcTemplate.queryForObject(
                "select id, group_name from t_group where id = ?",
                groupRowMapper,
                id);

        return group;
    }

    @Override
    public List<Group> list() {

        List<Group> groups = this.jdbcTemplate.query(
                "select id, group_name from t_group", groupRowMapper);
        return groups;
    }

    @Override
    public int loadCountGroup() {
        return this.jdbcTemplate.queryForObject("select count(*) from t_group", Integer.class);
    }

    private final RowMapper<Group> groupRowMapper = (resultSet, rowNum) -> {
        Group group = new Group();
        group.setGroupname(resultSet.getString("group_name"));
        group.setId(resultSet.getInt("id"));
        return group;
    };
}
